#!/usr/bin/env python
# coding:utf-8

from main.units.interfaces import Backup


class MySqlBackup(Backup):
    """backup mysql database"""

    # default task name
    name = 'mysql-backup'

    # default task description
    desc = 'mysql backup'

    def __init__(self, *args, **kwargs):
        super(MySqlBackup, self).__init__(*args, **kwargs)

    def execute(self):
        try:
            host = self.kwargs.get('host')
            port = self.kwargs.get('port')
            user = self.kwargs.get('user')
            pwd = self.kwargs.get('pwd')
            database = self.kwargs.get('database')
            output = self.kwargs.get('output')
            mysql_dump = self.kwargs.get('mysqldump')
        except Exception as exception:
            return exception.message
        else:
            if host and port and user and pwd and database and output:
                cmd = r'"%s" -h %s -u%s -p%s %s > %s --verbose' % (mysql_dump, host, user, pwd,
                                                                   database, output)
                import subprocess
                return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()
            else:
                return "{} Arguments Error, Please check!".format(self.args)
